package com.wxtl.service;

import java.sql.Timestamp;

import org.springframework.stereotype.Service;

import com.wxtl.action.qo.LoginUser;
import com.wxtl.dao.UserDAO;
import com.wxtl.entity.User;
import com.wxtl.exception.ServiceException;
import com.wxtl.util.Constants;
import com.wxtl.util.DataGridModel;
import com.wxtl.util.MD5Util;
import com.wxtl.util.Page;
import com.wxtl.util.Status;

@Service
public class UserService {
	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public Page query(DataGridModel dgm,User user){
		return userDAO.query(dgm,user);
	}
	
	public void delete(int[] ids){
		userDAO.delete(ids);
	}
	
	public User getUserById(int id){
		return userDAO.getUserById(id);
	}
	
	public void add(User user){
		//判断用户名是否存在
		if(userDAO.getUser(user.getUsername(), 0)!=null){
			throw new ServiceException("用户名已存在!");
		}
		user.setPassword(MD5Util.getMD5String(Constants.PASSWORD+Constants.SALT));
		user.setSalt(Constants.SALT);
		userDAO.add(user);
	}
	
	public void update(User user){
		//判断用户名是否存在
		if(userDAO.getUser(user.getUsername(), user.getUserId())!=null){
			throw new ServiceException("用户名已存在!");
		}
		userDAO.update(user);
	}
	
	public User getUserByNameAndPwd(LoginUser loginUser){
		//设置md5的密码
		loginUser.setPassword(MD5Util.getMD5String(loginUser.getPassword()+Constants.SALT));
		User user = userDAO.getUserByNameAndPwd(loginUser);
		if(user==null || user.getState()==Status.SYS_STATE_DELETE)
			throw new ServiceException("用户名或密码不存在");
		if(user.getState()==Status.SYS_STATE_BLOCK)
			throw new ServiceException("用户已锁定，请联系管理员");
		
		return user;
	}
	
	public User updateUserLoginInfo(LoginUser loginUser){
		//获取用户
		//loginUser.setPassword(MD5Util.getMD5String(loginUser.getPassword()));
		User user = this.getUserByNameAndPwd(loginUser);
		//设置ip date
		user.setLastIp(loginUser.getLoginIp());
		user.setLastLoginTime(new Timestamp(loginUser.getLoginDate().getTime()));
		this.update(user);
		
		return user;
	}
	
	public void modifyPwd(LoginUser loginUser){;
		loginUser.setPassword((MD5Util.getMD5String(loginUser.getPassword()+Constants.SALT)));
		User user = userDAO.getUserByNameAndPwd(loginUser);
		if(user==null){
			throw new ServiceException("旧密码不对");
		}
		user.setPassword(MD5Util.getMD5String(loginUser.getNewPwd1()+Constants.SALT));
		
		userDAO.update(user);
	}
}
